package com.sunpy.niohttp.codec;

import com.sunpy.niohttp.model.SunpyResponse;

import java.nio.charset.Charset;
import java.util.Map;

public class HttpEncoder {


    /**
     * HTTP/1.1 200 OK\r\n
     * Server: Apache-Coyote/1.1\r\n
     * Set-Cookie: SHAREJSESSIONID=8a0e17c5-379f-4fc1-85e0-81eb6056f480; Path=/; HttpOnly\r\n
     * Set-Cookie: rememberMe=deleteMe; Path=/mch; Max-Age=0; Expires=Thu, 17-Jan-2019 08:18:45 GMT\r\n
     * Content-Type: application/json;charset=UTF-8\r\n
     * Content-Length: 16\r\n
     * Date: Fri, 18 Jan 2019 08:18:45 GMT\r\n
     * \r\n
     * HTTP response 1/2
     * [Time since request: 0.052455000 seconds]
     * [Request in frame: 397]
     * [Next request in frame: 402]
     * [Next response in frame: 448]
     * File Data: 16 bytes
     */
    public String encodeHttpToStr(SunpyResponse response) {
        StringBuilder sb = new StringBuilder();
        // 响应行
        sb.append(response.getVersion()+ " ");
        sb.append(response.getCode()+ " ");
        sb.append(response.getStatus()+ "\n");
        // 响应头
        Map<java.lang.String, String> headers = response.getHeaders();

        headers.forEach((k, v) -> {
            sb.append(k + ":" + v);
            sb.append("\n");
        });
        // 空行
        sb.append("\n");
        // 响应体
        sb.append(response.getBody());
        return sb.toString();
    }


    public byte[] encodeHttp(SunpyResponse response) throws Exception {
        return encodeHttpToStr(response).getBytes();
    }
}
